import { Component, OnInit, Input } from '@angular/core';
import { LiveService } from 'src/app/service/live.service';
import { NzModalService } from 'ng-zorro-antd';
import { LivelibService } from 'src/app/service/livelib.service';
import EasyDanmaku from 'easy-danmaku-js';
declare var AVR
declare var THREE
declare var VR
@Component({
  selector: 'app-player',
  templateUrl: './player.component.html',
  styleUrls: ['./player.component.less']
})
export class PlayerComponent implements OnInit {
  @Input() roomId = ''
  room = {
    Content: '',
    Cover: null,
    Describe: '',
    FK_LiverGuid: '',
    LiverInfo: null,
    Name: '',
    PK_LiveRoomGuid: '',
    PlayUrl: '',
    Status: 1,
  }
  debug = false
  vr = null
  barrageIsShow = false//是否显示弹幕
  constructor(private nzModalService: NzModalService, private liveService: LiveService, private livelibService: LivelibService) { }
  err = null
  async ngOnInit(): Promise<void> {
    let playUrls = ''
    await this.liveService.getLiveRoom(this.roomId).then(res => {
      playUrls = JSON.parse(res['data']['PlayUrl'])
      this.room = res['data']
    })
    await this.liveService.getOnlineLive().then(res => {
      let onlineInfo = res['data']['OnlineInfo']
      if (onlineInfo) {
        let streamInfo = onlineInfo.LiveStreamOnlineInfo
        let thisLive = streamInfo.find(
          (w) => w.StreamName === this.roomId
        )
        if (thisLive) {
          this.err = null
        } else {
          this.err = '暂未开播'
        }
      }
    })
    this.danmaku = new EasyDanmaku({
      el: '#main',                        //弹幕挂载节点
      colourful: false,                         //彩色弹幕
      line: 2,                                //弹幕行数
      wrapperStyle: 'danmaku-wrapper',         //默认弹幕样式
      speed: 10,                                //弹幕播放速度
      runtime: 3,                              //播放一次的时常
      loop: false,                              //开启循环播放
      hover: false,                             //鼠标移入悬停
      onComplete: () => {
      },                                      //hover时 参数为该悬停元素（初始化属性hover必须为true）
      onHover: (dom) => {
      }
    })
    setTimeout(() => {
      if (!this.err) {
        this.init(playUrls)
      }
    }, 100);
  }
  danmaku = null
  sendDanmu(text) {
    console.log(text)
    this.danmaku.send(text, 'danmaku-wrapper', (e) => {
    })
  }
  init(playUrl) {
    let scene, renderer
    let container
    AVR.debug = true
    if (
      navigator.userAgent.match(/iphone os 14_0/i) ||
      navigator.userAgent.match(/iphone os 14_1/i) ||
      navigator.userAgent.match(/iphone os 14_3/i)
    ) {
      AVR.__fixHlsRender = true
    }
    renderer = new THREE.WebGLRenderer()
    renderer.setPixelRatio(window.devicePixelRatio)
    container = document.getElementById('main')
    container.appendChild(renderer.domElement)
    scene = new THREE.Scene()
    let vr
    this.vr = vr = new VR(scene, renderer, container, { fov: 80 })
    //vr.playText="<img src='img/play90.png' width='40' height='40'/>";
    vr.vrbox.radius = 600
    if (AVR.isCrossScreen()) {
      // 调整vr视窗偏移量
      vr.effect.separation = 1.2
    }
    vr.loadProgressManager.onLoad = function () {
      // 视频静音
    }
    let playUrlArray = []
    if (this.debug) {
      for (let key in playUrl) {
        playUrlArray.push({
          name: key,
          url: playUrl[key],
        })
      }
    } else {
      for (let key in playUrl) {
        playUrlArray.push({
          name: key,
          url: 'https://live.ysjlive.com' + playUrl[key],
        })
      }
    }
    AVR.useGyroscope = true
    vr.onPlay = async () => { }
    vr.showDanmu = () => {
      this.barrageIsShow = true
    }
    vr.closeDanmu = () => {
      this.barrageIsShow = false
    }
    playUrlArray.reverse()
    vr.init(playUrlArray, function () { }, true)

    vr.quality = playUrlArray[0].name
    vr.play(playUrlArray[0].url, vr.resType.sliceVideo, {
      autoplay: false,
    })
    vr.video.setAttribute('loop', 'loop')
    vr.video.crossOrigin = 'Anonymous'
    vr.video.onended = () => {
      this.err = '直播结束'
      this.nzModalService.success({
        nzTitle: '直播结束'
      })
    }
  }
  ngOnDestroy() {
    if (this.vr) this.vr.destroy()
  }
}
